<template>
  <section v-loading.fullscreen.lock="loading">
    <el-card class="margin-top">
      <div slot="header" class="clearfix relative">
        <el-row class="flex align-center ">
          <el-col :span="12">
            <span class="title-icon margin-right">货物信息</span>
            <el-button
              v-if="isEdit"
              type="primary"
              size="mini"
              icon="el-icon-download"
              @click="downloadCargoInfo"
            >
              导出货物信息
            </el-button>
          </el-col>
          <el-col
            :span="12"
            class="flex text-blue align-center justify-between"
          >
            <div>
              <span class="margin-lr">总产品个数：{{ totalAmount[0] }} </span>
              <span class="margin-lr">总箱数：{{ totalAmount[1] }} </span>
              <span class="margin-lr">总重量：{{ totalAmount[2] }} </span>
              <span class="margin-lr">总体积 ：{{ totalAmount[3] }} </span>
            </div>
            <div>
              <el-button
                v-if="isEdit && verifyShow.extGoodsEdit"
                type="success"
                size="mini"
                @click="changeCargoInfo"
              >
                保存
              </el-button>

              <i
                :class="{
                  'el-icon-arrow-down': show,
                  'el-icon-arrow-up': !show
                }"
                class="text-lg pointer margin-left"
                @click="show = !show"
              ></i>
            </div>
          </el-col>
        </el-row>
      </div>
      <el-collapse-transition>
        <div v-show="show">
          <hot-table ref="hotTable" :settings="hotSettings" :data="goodsInfo" />
        </div>
      </el-collapse-transition>
    </el-card>

    <ImportPop
      :uploadDialog.sync="uploadDialog"
      :dialogTitle="`批量导入信息`"
      v-on:uploadFn="uploadCargoInfo"
      :actionUrl="actionUrl"
      :fileName="`goodsInfoFile`"
    ></ImportPop>
  </section>
</template>

<script>
import ImportPop from "./ImportPop";
import { HotTable } from "@handsontable/vue";
// import Handsontable from 'handsontable'
import "handsontable/languages/zh-CN";
import globalData from "@/utils/config";
import * as constant from "@/store/yg/common/constant";
import { ajax } from "@/store/yg/common/utils";
import { checkRowsEmpty } from "@/utils";
export default {
  name: "OrderToOrderToOverseasWarehouseShipping",
  components: {
    HotTable,
    ImportPop
  },
  props: {
    verifyShow: {
      type: Object,
      default: function() {
        return {};
      }
    },
    waybillId: {
      type: Number,
      default: 1
    },
    actionUrl: {
      type: String,
      default: ""
    },
    goodsInfo: {
      type: Array,
      default: function(params) {
        return [{}];
      }
    },
    oldGoodsInfo: {
      type: Array,
      default: function(params) {
        return [{}];
      }
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    totalAmount() {
      let productNum = 0;
      let productCtns = 0;
      let productWeight = 0;
      let productVolume = 0;

      for (const i of this.goodsInfo) {
        if (i.productNum) {
          productNum += parseInt(Number(i.productNum));
        }
        if (i.productCtns) {
          productCtns += parseInt(Number(i.productCtns));
        }
        if (i.productWeight) {
          productWeight =
            (Number(productWeight) * 1000 +
              parseFloat(i.productWeight) * 1000) /
            1000;
        }
        if (i.productVolume) {
          productVolume =
            (Number(productVolume) * 1000 +
              parseFloat(i.productVolume) * 1000) /
            1000;
        }
      }

      return [productNum, productCtns, productWeight, productVolume];
    }
  },
  watch: {
    goodsInfo: {
      handler(newValue, oldValue) {
        if (newValue.length === 0) {
          this.$emit("update:goodsInfo", [{}]);
        }
      }
      // immediate: true,
      // deep: true
    },
    isEdit: {
      handler(newVal) {
        if (!newVal) {
          this.show = true;
        }
      },
      immediate: true,
      deep: true
    }
  },
  data() {
    return {
      uploadDialog: false,
      show: false,
      loading: false,
      waybillGoodsInfos: [{ sku: "tee" }, {}, {}, {}, {}],
      hotSettings: {
        rowHeaders: true, // 行表头
        stretchH: "all", // 所有列宽小于表宽时,填充满整个表 all（所有列填充）/last（最后一列）/none(不填充)
        licenseKey: globalData.licensekey,
        // 定义表结构
        colHeaders: [
          '<i style="color:red;margin-right:3px">*</i>旧FNSKU',
          "店铺链接	",
          '<i style="color:red;margin-right:3px">*</i>品名',
          '<i style="color:red;margin-right:3px">*</i>产品个数',
          "箱数",
          '<i style="color:red;margin-right:3px">*</i>重量',
          '<i style="color:red;margin-right:3px">*</i>体积'
        ],
        width: "100%",
        height: "auto",

        columns: [
          {
            data: "sku", // 指定所指列
            width: 100,
            allowEmpty: false,
            type: "text" // 类型
          },
          {
            data: "sellUrl",
            width: 100,
            type: "text"
          },
          {
            data: "productName",
            width: 100,
            allowEmpty: false,
            type: "text"
          },
          {
            data: "productNum",
            width: 100,
            allowEmpty: false,
            type: "numeric",
            numericFormat: {
              pattern: "0"
            }
          },
          {
            data: "productCtns",
            width: 100,
            type: "numeric",
            numericFormat: {
              pattern: "0"
            }
          },
          {
            data: "productWeight",
            width: 100,
            allowEmpty: false,
            type: "numeric",
            numericFormat: {
              pattern: "0.000"
            }
          },
          {
            data: "productVolume",
            width: 100,
            allowEmpty: false,
            type: "numeric",
            numericFormat: {
              pattern: "0.000"
            }
          }
        ],
        tableClassName: ["first-class-name", "second-class-name"],
        language: "zh-CN",
        contextMenu: ["row_above", "row_below", "remove_row", "alignment"], // 开启右键菜单
        afterCreateRow: (index, amount, source) => {
          console.log("index :>> ", index);
          // this.goodsInfo[index].waybillId = this.waybillId;
        },
        beforeRemoveRow: (index, amount, physicalRows, source) => {
          if (this.goodsInfo.length === 1) {
            this.goodsInfo.push({});
          }
        }
      }
    };
  },

  methods: {
    closeDialog() {
      this.uploadDialog = false;
    },
    async downloadCargoInfo() {
      const data = await ajax("downLoadGoodsInfo", {
        id: this.waybillId
      });
      console.log(
        "%cdata: ",
        "color: MidnightBlue; background: Aquamarine;",
        data
      );
      if (data.fileName) {
        window.open(constant.FILE_SERVER + data.fileName);
      } else {
        this.$message.error("导出失败！");
      }
    },
    uploadCargoInfo(file) {
      console.log("uploadCargoInfo", file);
    },
    changeCargoInfo() {
      for (const i of this.$refs.hotTable.data) {
        if (
          !i.sku ||
          !i.productName ||
          !i.productNum ||
          !i.productWeight ||
          !i.productVolume
        ) {
          this.$message.error("请填写必填信息");
          return;
        }
      }
      // TODO 保存操作
      this.saveInfo();
    },
    async saveInfo() {
      // 标记已删除数据
      this.loading = true;
      const arr = [];
      for (const i of this.oldGoodsInfo) {
        const target = this.goodsInfo.find(x => x.id === i.id);
        console.log("target :>> ", target);
        if (!target) {
          i.isDel = true;
          arr.push(i);
        }
      }
      const params = [...this.goodsInfo, ...arr];
      for (const i of params) {
        if (!i.waybillId) {
          i.waybillId = this.waybillId;
        }
      }
      const { code, message } = await ajax("batchSaveOrUpdateGoodsInfo", {
        waybillGoodsInfos: params
      });
      this.loading = false;
      if (code === 200) {
        this.$message({
          type: "success",
          message: "保存成功"
        });
      } else {
        this.$message.error(message);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.relative {
  .absolute {
    right: 10px;
    top: -40%;
  }
}
</style>
<style scoped>
/deep/ .el-card__header {
  padding: 8px 20px;
}
</style>
